package com.ruoyi.web.controller.upload;



import com.aliyun.oss.OSSClient;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.domain.AjaxResult;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@RestController
@RequestMapping("/upload")
@CrossOrigin
public class UploadController {

    @Value("${bucketName}")
    private String bucketName;
    @Value("${oss-img-path}")
    private String ossImgPath;
    @Value("${spring.cloud.alicloud.access-key}")
    private String accessKey;
    @Value("${spring.cloud.alicloud.secret-key}")
    private String secretkey;
    @Value("${spring.cloud.alicloud.oss.endpoint}")
    private String endpoint;


    //上传文件
    @ApiOperation(value = "上传新闻图片", tags = "")
    @ApiResponses({
            @ApiResponse(code = 0, message = "图片上传成功"),
            @ApiResponse(code = 500, message = "图片上传失败")
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "图片", dataType = "MultipartFile")
    })
    @PostMapping("/imgUpload")
    @Anonymous
    public AjaxResult up(@RequestParam MultipartFile file, HttpServletRequest request) throws IOException {
        OSSClient ossClient = new OSSClient(endpoint, accessKey, secretkey);
        InputStream inputStream = file.getInputStream();
        // 获取文件名
        String fileName = file.getOriginalFilename();
        // 获取文件后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        // 最后上传生成的文件名
        String finalFileName = UUID.randomUUID().toString().replaceAll("-", "") + suffixName;
        try {
            ossClient.putObject(bucketName, finalFileName, inputStream);
            ossClient.shutdown();
            System.out.println(finalFileName);
            System.out.println(ossImgPath + finalFileName);
            return AjaxResult.success().put("data",finalFileName).put("show",ossImgPath+finalFileName);
        } catch (Exception e) {
            return AjaxResult.error("上传失败");
        }

    }
}
